package com.shortvedio.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.shortvedio.base.mapper.ClassifyMapper;
import com.shortvedio.base.mapper.UserInterestMapper;
import com.shortvedio.base.model.Result;
import com.shortvedio.base.model.po.Classify;
import com.shortvedio.search.model.dto.ClassifyDto;
import com.shortvedio.search.model.es.ClassifyDoc;
import com.shortvedio.search.service.ClassifyService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ClassifyServiceImpl implements ClassifyService {

    @Autowired
    private RestHighLevelClient highLevelClient;

    @Autowired
    private ClassifyMapper classifyMapper;

    @Autowired
    private UserInterestMapper userInterestMapper;


    @Override
    public Result getLabel(String keyWord) throws IOException {
// 1.准备Request
        SearchRequest request = new SearchRequest("classify");
        // 准备DSL
        // 1.query
        request.source().query(QueryBuilders.matchQuery("name", keyWord));
        // 2.高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        // 3.发送请求
        SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 文档数组
        SearchHit[] hits = searchHits.getHits();

        List<ClassifyDto> classifyDtoList = new ArrayList<>();
        // 遍历
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ClassifyDoc classifyDoc = JSON.parseObject(json,ClassifyDoc.class);
            ClassifyDto classifyDto = new ClassifyDto();
            BeanUtils.copyProperties(classifyDoc,classifyDto);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    classifyDto.setHighlightName(name);
                }
            }
            classifyDtoList.add(classifyDto);
        }
        return Result.success(classifyDtoList);
    }

    @Override
    public Result getClassifyList(Integer type) {
        //通过类型获取
        LambdaQueryWrapper<Classify> classifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        classifyLambdaQueryWrapper.eq(Classify::getType,type);
        List<Classify> classifies = classifyMapper.selectList(classifyLambdaQueryWrapper);
        return Result.success(classifies);
    }

    @Override
    public Result getUserAddInterest(Long userId) {
        //通过userid获取
        List<Classify> userAddInterest = userInterestMapper.getUserAddInterest(userId);
        return Result.success(userAddInterest);
    }
}
